package icu.groot.alan.hotel.util.exception;

import icu.groot.alan.hotel.util.BizException;
import icu.groot.alan.hotel.util.ResultCodeEnum;
import icu.groot.alan.hotel.util.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 全局异常捕获，出现异常时以R的形式返回
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Result<Optional<Object>> catchException(BizException bizException, HttpServletResponse response) {
        response.setStatus(bizException.getErrorCode());
        log.error("BizException: ({}){}", bizException.getErrorCode(), bizException.getErrorMsg());
        return new Result<>(bizException.getErrorCode(), bizException.getErrorMsg(), Optional.empty());
    }
    @ExceptionHandler(value = Exception.class)
    public Result<String> catchException(Exception e, HttpServletResponse response) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(e.getClass().getName()).append(":");
        stringBuilder.append(e.getMessage());
        StackTraceElement[] elements = e.getStackTrace();
        if(elements.length > 0){
            StackTraceElement element = elements[0];
            stringBuilder.append("##function:").append(element.getClassName()).append("-").append(element.getMethodName()).append("-").append(element.getLineNumber());
        }
        response.setStatus(ResultCodeEnum.SYSTEM_EXCEPTION.getCode());
        e.printStackTrace();
        return new Result<>(ResultCodeEnum.SYSTEM_EXCEPTION.getCode(), ResultCodeEnum.SYSTEM_EXCEPTION.getMessage(), "");
    }
}
